import 'package:flutter/material.dart';
import '../../models/picker_models.dart';
import '../../utils/date_formatters.dart';
import '../../utils/localization_util.dart';
import '../common/custom_picker.dart';
import '../common/picker_item.dart';

class FilterDatePicker extends StatefulWidget {
  final DateTime initialDate;
  final ValueChanged<dynamic> onDateChanged;
  final FilterType type;
  final int yearsBack;
  final bool showLaterTime;
  final Locale locale;
  final WeekItemBuilder? weekItemBuilder;

  const FilterDatePicker({
    super.key,
    this.yearsBack = 3,
    required this.showLaterTime,
    required this.type,
    required this.locale,
    required this.initialDate,
    required this.onDateChanged,
    this.weekItemBuilder,
  });

  @override
  State<FilterDatePicker> createState() => _FilterDatePickerState();
}

class _FilterDatePickerState extends State<FilterDatePicker> {
  late final PickerLocalizations l10n;
  List<WeekData> _weekList = [];
  int _initialWeekIndex = 0;
  late int _selectedYear;
  late int _selectedMonth;

  @override
  void initState() {
    super.initState();
    l10n = PickerLocalizations(widget.locale);
    _initializeState();
  }

  void _initializeState() {
    switch (widget.type) {
      case FilterType.week:
        _weekList = generateWeekDataList(
            widget.initialDate, widget.yearsBack, widget.showLaterTime);
        _initialWeekIndex = _weekList.indexWhere((week) {
          final end = week.end.add(const Duration(days: 1));
          return widget.initialDate.isAfter(week.start.subtract(const Duration(seconds: 1))) &&
              widget.initialDate.isBefore(end);
        });
        if (_initialWeekIndex == -1) _initialWeekIndex = _weekList.length - 1;
        break;
      case FilterType.year:
        _selectedYear = widget.initialDate.year;
        break;
      case FilterType.month:
        _selectedYear = widget.initialDate.year;
        _selectedMonth = widget.initialDate.month;
        break;
    }
  }

  void _onFilterChanged() {
    late Map<String, int> resDate;
    if (widget.type == FilterType.year) {
      resDate = {"year": _selectedYear};
    } else if (widget.type == FilterType.month) {
      resDate = {"year": _selectedYear, "month": _selectedMonth};
    }
    widget.onDateChanged(resDate);
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 120,
      child: _buildPickerForType(),
    );
  }

  Widget _buildPickerForType() {
    switch (widget.type) {
      case FilterType.week:
        return _buildWeekPicker();
      case FilterType.month:
        return _buildMonthPicker();
      case FilterType.year:
        return _buildYearPicker();
    }
  }

  Widget _buildWeekPicker() {
    return CustomPicker(
      startValue: 0,
      endValue: _weekList.length - 1,
      initialValue: _initialWeekIndex,
      onValueChanged: (index) {
        final weekData = _weekList[index];
        widget.onDateChanged({
          "startTime": weekData.start,
          "endTime": weekData.end,
        });
      },
      itemBuilder: (context, value, isSelected) {
        final weekData = _weekList[value];
        // [MODIFIED] weekItemBuilder 现在传递 WeekData
        if (widget.weekItemBuilder != null) {
          // 为了向后兼容，我们仍然传递一个格式化好的字符串
          final formattedString = _formatWeekDataToString(weekData);
          return widget.weekItemBuilder!(context, formattedString, isSelected);
        }
        return _defaultWeekItemBuilder(context, weekData, isSelected);
      },
    );
  }

  // [NEW] 一个辅助方法，用于向后兼容 weekItemBuilder
  String _formatWeekDataToString(WeekData data) {
    final dateRange = "${formatDate(data.start)}~${formatDate(data.end)}";
    final weekText = data.isThisWeek ? l10n.thisWeek : l10n.week(data.weekOfYear);
    return "$dateRange($weekText)";
  }

  Widget _buildMonthPicker() {
    final now = DateTime.now();
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 32),
      child: Row(
        children: [
          Expanded(
            child: CustomPicker(
              startValue: now.year - widget.yearsBack,
              endValue: now.year,
              initialValue: _selectedYear,
              onValueChanged: (value) {
                setState(() {
                  _selectedYear = value;
                  if (!widget.showLaterTime &&
                      _selectedYear == now.year &&
                      _selectedMonth > now.month) {
                    _selectedMonth = now.month;
                  }
                });
                _onFilterChanged();
              },
              itemBuilder: (context, value, isSelected) => PickerItem(
                  value: value.toString(), suffix: l10n.year, isSelected: isSelected),
            ),
          ),
          Expanded(
            child: CustomPicker(
              startValue: 1,
              endValue: !widget.showLaterTime && _selectedYear == now.year
                  ? now.month
                  : 12,
              initialValue: _selectedMonth,
              onValueChanged: (value) {
                setState(() => _selectedMonth = value);
                _onFilterChanged();
              },
              itemBuilder: (context, value, isSelected) => PickerItem(
                  value: value.toString().padLeft(2, '0'),
                  suffix:  l10n.month,
                  isSelected: isSelected),
            ),
          )
        ],
      ),
    );
  }

  Widget _buildYearPicker() {
    final now = DateTime.now();
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 32.0),
      child: CustomPicker(
        startValue: now.year - widget.yearsBack,
        endValue: now.year,
        initialValue: _selectedYear,
        onValueChanged: (value) {
          setState(() => _selectedYear = value);
          _onFilterChanged();
        },
        itemBuilder: (context, value, isSelected) => PickerItem(
            value: value.toString(), suffix:  l10n.year, isSelected: isSelected),
      ),
    );
  }

  // [REFACTORED] 默认的周 item 构建器也使用 RichText 优化
  Widget _defaultWeekItemBuilder(
      BuildContext context, WeekData weekData, bool isSelected) {
    final dateRange = "${formatDate(weekData.start)}~${formatDate(weekData.end)}";
    final weekText = "(${weekData.isThisWeek ? l10n.thisWeek : l10n.week(weekData.weekOfYear)})";

    final Color textColor = isSelected ? const Color(0xFF3482FF) : Colors.black54;
    final FontWeight fontWeight = isSelected ? FontWeight.bold : FontWeight.normal;

    return Center(
      child: RichText(
        text: TextSpan(
          style: DefaultTextStyle.of(context).style.copyWith(
            color: textColor,
            fontWeight: fontWeight,
          ),
          children: [
            TextSpan(
              text: dateRange,
              style: TextStyle(fontSize: isSelected ? 18 : 14),
            ),
            const TextSpan(text: ' '),
            TextSpan(
              text: weekText,
              style: TextStyle(fontSize: isSelected ? 14 : 11),
            ),
          ],
        ),
      ),
    );
  }
}
